package com.taplinker.client.im;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;

import com.taplinker.client.AppConfigContext;
import com.taplinker.client.im.rpc.ImSocketTemplate;
import com.taplinker.core.Resource;
import com.taplinker.core.ResourceManager;
import com.taplinker.core.rpc.socket.SocketConfigContext;
import com.taplinker.core.rpc.socket.SocketTemplate;
import com.taplinker.core.util.LogUtil;

public class SocketTemplateContext implements Resource{
	private Timer time;
	private SocketTemplate template;
	private static SocketTemplateContext instance;
	
	public static SocketTemplateContext getInstance() {
		if (instance!=null) {
			return instance;
		}
		synchronized (SocketTemplateContext.class) {
			if (instance == null) {
				instance = new SocketTemplateContext();
				ResourceManager.getInstance().addResource(instance);
	 		}
		}
		return instance;
	}
	
	public void initialize(Context context) {
		if(template != null&&template.isConnected()) {
			return;
		}
		
		template = new ImSocketTemplate(new SocketConfigContext(AppConfigContext.IM_HOST, AppConfigContext.IM_PORT));
		
		time = new Timer();
		time.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				LogUtil.d("socket", "--------heart--------");
				template.sendMessage();
			}
		}, 1000*2, 1000*60*5);
		
	}
	
	public SocketTemplate getTemplate() {
		return template;
	}

	@Override
	public void releaseResource() {
		template.releaseResource();
		time.cancel();
		time = null;
	}

	@Override
	public void clear() {
		
	}
}
